#include "command_line.h"
#include "../base/debug.h"
#include "../base/error.h"
#include "../base/logging.h"
#include "../base/command_line_parser.h"
#include "pcagent_command_line_validator.h"

TCHAR* GetCmdLindTail(const TCHAR* cmd_line)
{
	ASSERT1(cmd_line);
	bool in_quote = false;

	// Skip past program name (first token in command line).
	// Check for and handle quoted program name.
	while ((*cmd_line) > _T(' ') || (*cmd_line && in_quote))
	{
		// Flip the in_quote if current character is '"'
		if  (*cmd_line == _T('"'))
			in_quote = !in_quote;
		++cmd_line;
	}

	// Skip past any white space preceeding the second token.
	while (*cmd_line && (*cmd_line <= _T(' ')))
		cmd_line++;

	return const_cast<TCHAR*>(cmd_line);
}

HRESULT ParseCommandLine(const TCHAR* cmd_line, CommandLineArgs* args)
{
	ASSERT1(cmd_line);
	ASSERT1(args);
	CORE_LOG(L3, (_T("[ParseCommandLine][%s]"), cmd_line));

	CommandLineParser parser;
	HRESULT hr = parser.ParseFromString(cmd_line);
	if (FAILED(hr))
	{
		CORE_LOG(LE, (_T("[ParseCommandLine][ParseFromString failed][0x%x]"), hr));
		return hr;
	}

	PCAgentCommandLineValidator validator;
	hr = validator.Setup();
	if (FAILED(hr))
	{
		CORE_LOG(LE, (_T("[ParseCommandLine][Validator Setup failed][0x%x]"), hr));
		return hr;
	}

	hr = validator.Validate(&parser, args);
	if (FAILED(hr))
	{
		CORE_LOG(LE, (_T("[ParseCommandLine][Validator Validate failed][0x%x]"), hr));
		return hr;
	}

	return S_OK;
}